package com.rub.prajna.av.controller

import com.rub.prajna.av.view.VideoToImageView
import com.rub.prajna.core.video.VideoHandler
import javafx.collections.FXCollections
import javafx.embed.swing.SwingFXUtils
import javafx.event.ActionEvent
import javafx.fxml.FXML
import javafx.scene.control.Alert
import javafx.scene.control.ButtonType
import javafx.scene.image.Image
import java.io.File
import java.net.URL
import java.util.*
import javax.imageio.ImageIO


/**
 * ?.表示当前对象如果为空则不执行，!!.表示当前对象如果为空也执行，然后会抛出空异常
 */
class VideoToImageController : VideoToImageView() {


    @FXML
    private fun onActionBtnOK(event: ActionEvent) {
        val cutTime = cutTime.value
        val imageType = imageType.value
        val inputFile = inputFile.text

        if (inputFile == null || "" == inputFile) {
            Alert(Alert.AlertType.ERROR, "请选择视频文件", ButtonType.OK).show()
            return
        }
        if (cutTime == null) {
            Alert(Alert.AlertType.ERROR, "请输入时间", ButtonType.OK).show()
            return
        }
        if (imageType == null || imageType == "") {
            Alert(Alert.AlertType.ERROR, "请选择图片类型", ButtonType.OK).show()
            return
        }

        val videoHandler = VideoHandler(inputFile, imageType as String, cutTime).cutImage()

        //成功设置输出路径
        if (videoHandler.getStatus()) {
            outputFile.text = videoHandler.getOutPutFile()
            btnLook.isDisable = false

        }

    }

    @FXML
    private fun onActionReset() {
        //fxml配置默认最小值为1，其实这可以不用设置都可以.小于1的都无效，大于1才生效.
        cutTime.valueFactory.apply { value = 1 }
        imageType.selectionModel.clearSelection()
        inputFile.text = ""

    }

    @FXML
    private fun btnLookAction() {
        val filePath = outputFile?.text
        if (filePath != null && filePath != "") {
            val image: Image = SwingFXUtils.toFXImage(ImageIO.read(File(filePath)), null)
            this.imageView.image = image
        }
    }

    override fun initialize(location: URL?, resources: ResourceBundle?) {
        imageType.items = FXCollections.observableArrayList(initImageType())
        imageType.selectionModel.selectFirst()
        outputFile.isEditable = false
        cutTime.isEditable = true
        btnLook.isDisable = true

    }


}
 


